package com.jiangnan.service;

import com.jiangnan.utils.CollectionUtils;
import com.jiangnan.utils.LogUtils;
import jpcap.JpcapCaptor;
import jpcap.JpcapWriter;
import jpcap.packet.Packet;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class PacketCutTask extends Thread {
    private JpcapCaptor captor = null;
    private JpcapWriter writer;
    private static final int CUT_PACKET_SIZE = 1000000;
    private final File in, out;
    private final int packetCutSize;

    public PacketCutTask(File in, File out, int packetCutSize) {
        this.in = in;
        this.out = out;
        this.packetCutSize = packetCutSize == 0 ? CUT_PACKET_SIZE : packetCutSize;
    }


    public void cutPacket() {
        long index = 0;
        List<Packet> packetList = new ArrayList<>();
        String absolutePath = in.getAbsolutePath();
        try {
            captor = JpcapCaptor.openFile(absolutePath);
            while (true) {
                Packet packet = captor.getPacket();
                if (packet == null || packet.data == null) {
                    savePcapFile(packetList, out, index);
                    packetList.clear();
                    break;
                }
                for (int i = 1; i <= packetCutSize; i++) {
                    packetList.add(packet);
                    if (i == packetCutSize) {
                        savePcapFile(packetList, out, index);
                        packetList.clear();
                        index++;
                    }
                }
            }
        } catch (IOException exception) {
            LogUtils.log(exception.getMessage() + "注意是否中文路径");
        } finally {
            writer.close();
        }

    }



    private void savePcapFile(List<Packet> packetList, File out, long index) {
        if (CollectionUtils.isEmpty(packetList)) {
            return;
        }
        String absolutePath = out.getAbsolutePath() + "/cut_" + index + ".pcap";
        try {
            writer = JpcapWriter.openDumpFile(captor, absolutePath);
            for (Packet packet : packetList) {
                writer.writePacket(packet);
            }
            LogUtils.log(index + "保存文件成功");
        } catch (IOException exception) {
            LogUtils.log(exception.getMessage());
        }
    }

    @Override
    public void run() {
        cutPacket();
    }
}
